<?php

namespace app\api\controller;


use app\admin\model\yexam\ExamPapersUser;
use app\admin\model\yexam\Question;
use app\admin\model\yexam\QuestionError;
use app\admin\model\yexam\Unit;
use app\common\controller\Api;

/**
 * @ApiSector (用户反馈)
 * @ApiRoute (/api/feedback)
 * @ApiWeight (999)
 */

class Feedback extends Api
{
    protected $noNeedLogin = [""];
    protected $noNeedRight = ["*"];

    /**
     * @ApiTitle (添加信息反馈)
     * @ApiRoute (add)
     * @ApiParams (name=content,type=string,required=true,description=反馈的内容)
     * @ApiParams (name=tupe,type=integer,required=true,description=反馈的类型)
     * @ApiHeaders (name=token,type=string,rqeuired=true,description=token)
     * @ApiReturnParams (name=string,type=string,required=true,sample=反馈提交成功)
     * @ApiReturn ({msg: "反馈提交成功"})
     */
    public function add(){
        $model = new \app\admin\model\Feedback();
        $model->content = $this->request->param('content');
        if ($model->content == '')
            $this->error('请填写内容');
        $model->type = $this->request->param('type');
        $model->uid = $this->auth->id;
        $model->mobile = $this->auth->mobile;
        $model->add_time = time();
        $model->save();
        $this->success("反馈提交成功");
    }
    /**
     * @ApiTitle (错题反馈),
     * @ApiMethod (POST)
     * @ApiParams (name=id,type=string,required=true,description=试题id)
     * @ApiParams (name=content,type=string,required=true,description=反馈内容)
     * @ApiParams (name=type,type=integer,required=true,description=反馈类型)
     * @ApiParams (name=answer,type=string,required=true,description=答案)
     * @ApiParams (name=subject_id,type=integer,required=true,description=科目id)
     * @ApiReturn ({msg: "反馈成功"})
     */
    //=================   ==============
    public function feedbackError()
    {
        $id = $this->request->param('id');
        $content = $this->request->param('content');
        $type = $this->request->param('type');
        $answer = $this->request->param('answer');
        $subjectId = $this->request->param('subject_id');
        if ($content == "") $this->error('内容不能为空');
        if ($id == 0) $this->error('请选择试题');
        if ($type == '') $this->error('请选择反馈类型');
        $error = new QuestionError();
        $error->insert([
            'question_id' => $id,
            'content' => $content,
            'type' => $type,
            'time' => time(),
            'feedback_person' => $this->auth->username,
            "subject_id" => $subjectId,
            'answer' => $answer
        ]);
        $this->success('反馈成功');
    }
    /**
     * @ApiTitle (手动组题),
     * @ApiMethod (POST)
     * @ApiParams (name=config,type=object,required=true,description=组卷的配置)
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    //==============
    public function handleExam()
    {
        $param = $this->request->param('config/a');
        if (!isset($param['units'])) $this->error('请选择章节');
        $units = $param['units']; // 章节
        $subjectId = $param['subject_id'];
        $question = $param['question'];
        $total_score = 0;
        $question_ids = [];
        $questiontype = [];
        $num = 0;
        foreach ($question as $key => $value)
        {
            if ($value['number'] < 0) $this->error('试题数量不正确');
            if ($value['score'] < 0) $this->error('分数不正确');
            $total_score += $value['score']*$value['number'];
            array_push($questiontype,$key);
            $num += $value['number'];
        }
        if ($num == 0) $this->error('试题量不正确');
        $unit = new Unit();
        $result = $unit->where('pid','in',$units)->field('id')->limit(100)->orderRaw("rand()")->select();
        if ($param['rule'] == 1) // ==== 随机抽题
        {
            $unitIds = [];
            foreach ($result as $v) array_push($unitIds,$v['id']);
        }elseif ($param['rule'] == 2) // ===== 抽取错题
        {
            $where = [];
        }else{ //================ 抽取未答的题目
            $where = [];
        }
        $questionModel = new Question();
        $res = $questionModel->where('unit_id','in',$unitIds)->orderRaw("rand()")->field('id,questiontype')->whereOr('questiontype','in',$questiontype)->limit($num)->select();
        $extend_score = [];
        foreach ($res as $kk)
        {
            $extend_score[$kk['id']] = $question[$kk['questiontype']]['score'];//==== 试题对应的分数
            array_push($question_ids,$kk['id']);
        }
        $paperUser = new ExamPapersUser();
        $paperUser->save([
            'subject_id' => $subjectId,
            'user_id' => $this->auth->id,
            'exam_name' => date('Y-m-d').'手工组卷',
            'total_score' => $total_score,
            'add_time' => time(),
            'question_ids' => implode(',',$question_ids),
            'extend_score' => json_encode($extend_score)
        ]);
        $this->success('添加成功',implode(',',$question_ids));
    }
    /**
     * @ApiTitle (错题反馈列表)
     * @ApiMethod (GET)
     * @ApiParams (name=type,type=string,required=true,descrption=反馈类型)
     * @ApiReturn ({msg:"ok",data:"[]"])
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getFeedbackList()
    {
        $type = $this->request->param('type');
        $feedback =new \app\admin\model\yexam\QuestionError();
        $lists = $feedback->where('feedback_person',$this->auth->username)->where('mark',$type)->select()->toArray();
        $question = new Question();
        foreach ($lists as $key => $va){
            $lists[$key]['title'] = $question->where('id',$va['question_id'])->value('question_name');
            $lists[$key]['content'] = $va['content'];
            $lists[$key]['reply'] = $va['reply'];
        }
        $this->success('ok',$lists);
    }
}